package com.wbao.dianniu.update;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.wbao.dianniu.R;
import com.wbao.dianniu.data.VersionData;
import com.wbao.dianniu.listener.ICheckUpdateListener;
import com.wbao.dianniu.manager.CheckUpdateManager;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class UpdateManager implements ICheckUpdateListener {
    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    /* 下载服务器版本文件	*/
    private static final int DOWNLOAD_VERSION = 3;
    /* 未检测到更新	*/
    private static final int NO_UPDATE = 4;
    /**
     * 下载失败，权限异常
     */
    private static final int DOWNLOAD_FAIL_NOPREMISS = 5;
    /* 保存解析的XML信息 */
//	HashMap<String, String> mHashMap;
    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private Activity mContext;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;
    private static ICheckCompletedListener mListener;
    private CheckUpdateManager manager;
    private String apkUrl = null;
    private VersionData versionData;

    public interface ICheckCompletedListener {
        void checkCompleted();

        void noCheck();

        void noPermission();
    }

    public void addCheckListener(ICheckCompletedListener listener) {
        mListener = listener;
    }

    public void removeCheckListener() {
        manager.removeCheckUpdateListener(this);
        mListener = null;
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    installApk();
                    break;
                case DOWNLOAD_VERSION:
                    if (null != mListener) {
                        mListener.checkCompleted();
                    }
                    // 显示提示对话框
                    showNoticeDialog();
                    break;
                case NO_UPDATE:
                    if (null != mListener) {
                        mListener.noCheck();
                    }
                    break;
                case DOWNLOAD_FAIL_NOPREMISS:
                    if (null != mListener) {
                        mListener.noPermission();
                    }
                    break;
                default:
                    break;
            }
        }

    };

    public UpdateManager(Activity context) {
        this.mContext = context;
        manager = new CheckUpdateManager(mContext);
        manager.addCheckUpdateListener(this);
        versionData = new VersionData();
    }

    /**
     * 检测软件更新
     */
    public void checkUpdate() {
        cancelUpdate = false;
        manager.checkUpdate();
    }

    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final Dialog dialog = new Dialog(mContext, R.style.custom_Dialog);
        View layout = inflater.inflate(R.layout.version_update_dialog, null);
        TextView versionName = layout.findViewById(R.id.update_versionName);
        TextView textView = layout.findViewById(R.id.update_content_desc);
        Button cancel = layout.findViewById(R.id.update_cancel);
        Button confirm = layout.findViewById(R.id.update_confirm);
        versionName.setText(versionData.getVersionName() == null ? "" : versionData.getVersionName());
        if (versionData.isMustUpdate()) {
            cancel.setVisibility(View.GONE);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancelable(false);
        } else {
            cancel.setVisibility(View.VISIBLE);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancelable(true);
        }
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                // 显示下载对话框
                showDownloadDialog();
                // 调用浏览器 下载
//                downloadAPkForUrl(versionData.getApkUrl());
            }
        });
        textView.setText(versionData.getNewFeature() == null ? "" : versionData.getNewFeature());
        textView.setMovementMethod(ScrollingMovementMethod.getInstance());
        dialog.setContentView(layout);
        dialog.show();
    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog() {
        mDownloadDialog = new Dialog(mContext, R.style.custom_Dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.softupdate_progress, null);
        mProgress = v.findViewById(R.id.update_progress);
        Button cancel = v.findViewById(R.id.cancelBtn);

        if (versionData.isMustUpdate()) {
            mDownloadDialog.setCancelable(false);
            mDownloadDialog.setCanceledOnTouchOutside(false);
            cancel.setVisibility(View.GONE);
        } else {
            mDownloadDialog.setCancelable(false);
            mDownloadDialog.setCanceledOnTouchOutside(false);
            cancel.setVisibility(View.VISIBLE);
        }

        cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mDownloadDialog.dismiss();
                // 设置取消状态
                cancelUpdate = true;
            }
        });
        mDownloadDialog.setContentView(v);
        mDownloadDialog.show();
        // 现在文件
        downloadApk();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }

    /**
     * 下载文件线程
     *
     * @author coolszy
     * @date 2012-4-26
     * @blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";

                    if (null == apkUrl) {
                        return;
                    }
                    URL url = new URL(apkUrl);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, "dianniu.apk");
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                } else {
                    if (null != mDownloadDialog) {
                        mDownloadDialog.dismiss();
                    }
                    Notification.showToastMsg(mContext, "未检测到存储卡，无法下载");
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
                mHandler.sendEmptyMessage(DOWNLOAD_FAIL_NOPREMISS);
            }
            // 取消下载对话框显示
            if (null != mDownloadDialog) {
                mDownloadDialog.dismiss();
            }
        }
    }

    /**
     * 安装APK文件
     */
    private void installApk() {
        File apkfile = new File(mSavePath, "dianniu.apk");
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri apkUri = FileProvider.getUriForFile(mContext, "com.wbao.dianniu.fileprovider", apkfile);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);
    }

    @Override
    public void onCheckFailure(int errorCode, String errorMsg) {
        // TODO Auto-generated method stub
        Message msg = new Message();
        msg.what = NO_UPDATE;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onCheckSuccess(VersionData versionData) {
        if (null == versionData) {
            Message msg = new Message();
            msg.what = NO_UPDATE;
            mHandler.sendMessage(msg);
            return;
        }
        this.versionData = versionData;
        int serviceCode = versionData.getVersionCode();
        int versionCode = Utils.getVersionCode(mContext);
        apkUrl = versionData.getApkUrl();
        // 版本判断
        if (serviceCode > versionCode) {
            Message msg = new Message();
            msg.what = DOWNLOAD_VERSION;
            mHandler.sendMessage(msg);
        } else {
            Message msg = new Message();
            msg.what = NO_UPDATE;
            mHandler.sendMessage(msg);
        }
    }


}
